﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;

namespace BW.Mes.WinForms.Process.Aduit
{
    public partial class AuditForm : DevExpress.XtraEditors.XtraForm
    {
        // Define delegate and event for audit completion
        public delegate void AuditCompletedEventHandler(object sender, EventArgs e);
        public event AuditCompletedEventHandler AuditCompleted;
        
        public string WorkflowId { get; set; }
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "http://120.26.197.100:8022";

        // 定义表单控件
        private ComboBoxEdit statusComboBox;
        private MemoEdit remarkMemoEdit;
        private ComboBoxEdit auditTypeComboBox;
        private SimpleButton confirmButton;

        public AuditForm()
        {
            InitializeComponent();
            
            // 初始化HTTP客户端
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(
                new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 初始化控件
            InitializeControls();
        }

        private void InitializeControls()
        {
            // 设置窗体初始大小
            this.ClientSize = new Size(380, 280);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;
            
            // 状态标签
            LabelControl statusLabel = new LabelControl();
            statusLabel.Text = "审批状态:";
            statusLabel.Location = new Point(30, 33);
            statusLabel.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
            statusLabel.Size = new Size(80, 20);
            statusLabel.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            this.Controls.Add(statusLabel);
            
            // 状态选择下拉框
            statusComboBox = new ComboBoxEdit();
            statusComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            statusComboBox.Properties.Items.AddRange(new string[] { "通过", "拒绝" });
            statusComboBox.SelectedIndex = 0;
            statusComboBox.Location = new Point(120, 30);
            statusComboBox.Size = new Size(200, 24);
            this.Controls.Add(statusComboBox);
            
            // 意见标签
            LabelControl remarkLabel = new LabelControl();
            remarkLabel.Text = "审批意见:";
            remarkLabel.Location = new Point(30, 73);
            remarkLabel.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
            remarkLabel.Size = new Size(80, 20);
            remarkLabel.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            this.Controls.Add(remarkLabel);
            
            // 意见输入框
            remarkMemoEdit = new MemoEdit();
            remarkMemoEdit.Properties.NullText = "请输入审批意见...";
            remarkMemoEdit.Location = new Point(120, 70);
            remarkMemoEdit.Size = new Size(200, 80);
            this.Controls.Add(remarkMemoEdit);
            
            // 操作类型标签 - 调整位置与样式
            LabelControl auditTypeLabel = new LabelControl();
            auditTypeLabel.Text = "操作类型:";
            auditTypeLabel.Location = new Point(30, 163);
            auditTypeLabel.AutoSizeMode = DevExpress.XtraEditors.LabelAutoSizeMode.None;
            auditTypeLabel.Size = new Size(80, 20);
            auditTypeLabel.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            this.Controls.Add(auditTypeLabel);
            
            // 操作类型下拉框 - 调整位置
            auditTypeComboBox = new ComboBoxEdit();
            auditTypeComboBox.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            auditTypeComboBox.Properties.Items.AddRange(new string[] { "审批" });
            auditTypeComboBox.SelectedIndex = 0;
            auditTypeComboBox.Location = new Point(120, 160);
            auditTypeComboBox.Size = new Size(200, 24);
            this.Controls.Add(auditTypeComboBox);
            
            // 确认按钮
            confirmButton = new SimpleButton();
            confirmButton.Text = "确认审批";
            confirmButton.Location = new Point(120, 210);
            confirmButton.Size = new Size(90, 30);
            confirmButton.Click += checkButton1_CheckedChanged;
            this.Controls.Add(confirmButton);
            
            // 取消按钮
            SimpleButton cancelButton = new SimpleButton();
            cancelButton.Text = "取消";
            cancelButton.Location = new Point(230, 210);
            cancelButton.Size = new Size(90, 30);
            cancelButton.Click += (sender, e) => this.Close();
            this.Controls.Add(cancelButton);
        }

        public AuditForm(string workflowId) : this()
        {
            WorkflowId = workflowId;
            // 在窗体标题中显示工作流ID
            this.Text = $"审批 - 工作流ID: {workflowId}";
        }

        private async void checkButton1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                // 获取表单上的状态、意见和操作类型
                string status = GetStatusFromForm();
                string remark = GetRemarkFromForm();
                string auditType = GetAuditTypeFromForm();
                
                // 创建请求参数对象
                var auditData = new
                {
                    WorkflowId = this.WorkflowId,
                    Status = status,
                    Remark = remark,
                    AuditType = auditType
                };
                
                // 将对象序列化为JSON
                string jsonData = JsonConvert.SerializeObject(auditData);
                
                // 设置HTTP请求内容
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                
                // 发送POST请求
                string url = $"{_apiBaseUrl}/T5/OperationModel/AuditProcess";
                var response = await _httpClient.PostAsync(url, content);
                
                // 确保请求成功
                response.EnsureSuccessStatusCode();
                
                // 读取并处理响应
                var responseContent = await response.Content.ReadAsStringAsync();
                dynamic apiResult = JsonConvert.DeserializeObject(responseContent);
                
                if (apiResult != null && (int)apiResult.success == 200)
                {
                    // Trigger the AuditCompleted event
                    AuditCompleted?.Invoke(this, EventArgs.Empty);
                    
                    XtraMessageBox.Show("审批成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK; // 设置对话框结果为OK，以便父窗体知道操作成功
                    this.Close();
                }
                else
                {
                    string errorMessage = apiResult != null ? (string)apiResult.message : "未知错误";
                    XtraMessageBox.Show($"审批失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException httpEx)
            {
                XtraMessageBox.Show($"HTTP请求错误: {httpEx.Message}\n请确认API服务是否启动并可访问。", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        // 从表单控件获取状态
        private string GetStatusFromForm()
        {
            if (statusComboBox != null && statusComboBox.SelectedItem != null)
                return statusComboBox.SelectedItem.ToString();
            return "通过"; // 默认值
        }
        
        // 从表单控件获取备注
        private string GetRemarkFromForm()
        {
            if (remarkMemoEdit != null)
                return remarkMemoEdit.Text;
            return ""; // 默认值
        }
        
        // 从表单控件获取操作类型
        private string GetAuditTypeFromForm()
        {
            if (auditTypeComboBox != null && auditTypeComboBox.SelectedItem != null)
                return auditTypeComboBox.SelectedItem.ToString();
            return "审批"; // 默认值
        }
    }
}